package com.cloud.goods.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.goods.mapper.TbItemMapper;
import com.cloud.goods.service.ITbItemService;
import com.cloud.mall.goods.TbItem;
import com.cloud.mall.goods.dto.ItemStockDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2021-07-05
 */
@Service
public class TbItemServiceImpl extends ServiceImpl<TbItemMapper, TbItem> implements ITbItemService {

    @Autowired
    private TbItemMapper tbItemMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean decreaseGoodsAmount(List<ItemStockDto> itemStockDtos) {
//        锁定数据库数据
        List<Long> ids = itemStockDtos.stream().map(itemStockDto -> itemStockDto.getItemId()).collect(Collectors.toList());
        List<TbItem> tbItems = tbItemMapper.selectForLockGoods(ids);
        if (tbItems == null && tbItems.size() == 0) {
            throw new RuntimeException("未找到商品信息");
        }
        if (tbItems.size() < itemStockDtos.size()) {
            throw new RuntimeException("部分商品不存在");
        }

        tbItems.forEach(tbItem -> {
            for (ItemStockDto itemStockDto : itemStockDtos) {
                if (itemStockDto.getItemId().equals(tbItem.getId())) {
                    if (tbItem.getNum() >= itemStockDto.getNum()) {
                        tbItemMapper.decreaseGoodsAmount(itemStockDto);
                    } else {
                        throw new RuntimeException("库存不足！");
                    }
                }
            }
        });
        return true;
    }
}
